package main

import (
	"github.com/adjust/redismq"
	"fmt"
	"log"
	"github.com/nofuck/instagram"
	"sync"
	"clannad/commontool"
	"strconv"
	"os"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"regexp"
)

const (
	IP           = "123.207.14.208"
	Port         = "6379"
	Password     = "firely0506"
	DBName       = 0
	QueueName    = "ins_urls"
	DownloadPath = "/data/instagram/img/"
)

const (
	Endpoint        = "oss-cn-shenzhen.aliyuncs.com"
	AccessKeyId     = "LTAIJen9j9bhbTEQ"
	AccessKeySecret = "gHN87NTN1QnJvyRMyaGcuF0AYzaRRv"
	Bucket          = "wechat-lvyun"
)

func main() {
	chanImg := make(chan string, 3)
	wait := &sync.WaitGroup{}

	go prepareImgUrl(chanImg)
	for i := 0; i < 2; i++ {
		wait.Add(1)
		go downloadImg(chanImg, wait, i)
	}
	wait.Wait()
	fmt.Println("task is over!")
}

func prepareImgUrl(ch chan string) {
	log.Println("开始连接Redis...")
	log.Println("缓冲通道容量为" + strconv.Itoa(cap(ch)))

	queue, err := redismq.SelectQueue(IP, Port, Password, DBName, QueueName)
	if err != nil {
		fmt.Println("Redis连接错误:" + err.Error())
		os.Exit(110)
	}
	consumerName := "c_" + commontool.RandStr(16)
	log.Println("消费者名称：" + consumerName)
	consumer, err := queue.AddConsumer(consumerName)
	if err != nil {
		log.Println(err)
		os.Exit(110)
	}
	consumer.ResetWorking()
	for {
		p, err := consumer.Get()
		if err != nil {
			log.Println(err)
		}
		imgUrl := p.Payload
		log.Println("向通道Push数据:" + imgUrl)
		ch <- imgUrl
		err = p.Ack()
		if err != nil {
			log.Println(err)
		}
	}
	defer consumer.Quit()
}

func downloadImg(ch chan string, wait *sync.WaitGroup, i int) {
	log.Println("协程" + strconv.Itoa(i) + "已启动")
	for {
		select {
		case imgUrl, ok := <-ch:
			if !ok {
				continue
			}
			log.Println("[info] Start download image, " + imgUrl)
			ret := instagram.SaveImage(imgUrl, DownloadPath)

			if !ret {
				fmt.Println("下载失败，" + imgUrl)
			} else {
				fmt.Println("图片下载成功，" + imgUrl)
			}
			reg, _ := regexp.Compile(`(\w|\d|_)*.jpg`)
			imageName := reg.FindStringSubmatch(imgUrl)[0]
			if !uploadImg(imageName) {
				continue
			}
			fmt.Println("图片已上传至阿里OSS" + imageName)
		}
	}
	defer wait.Done()
	log.Println("协程" + strconv.Itoa(i) + "已关闭")
}

func uploadImg(fileName string) bool {
	client, err := oss.New(Endpoint, AccessKeyId, AccessKeySecret)
	if err != nil {
		log.Println(err.Error());
	}
	bucket, err := client.Bucket(Bucket)
	if err != nil {
		log.Println(err.Error())
	}
	error := bucket.PutObjectFromFile(fileName, DownloadPath+fileName)
	if error != nil {
		log.Println("上传文件失败" + error.Error());
	}
	return true
}
